package com.tjbank.cssys.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tjbank.cssys.domain.CkOrderAchievementForm;
import com.tjbank.cssys.domain.CkOrderRecoveryData;
import com.tjbank.cssys.repository.CkOrderAchievementFormMapper;
import com.tjbank.cssys.repository.CkOrderLoanIntelligenceDivisionMapper;
import com.tjbank.cssys.repository.CkOrderRecoveryDataMapper;
import com.tjbank.cssys.web.service.CkOrderAchievementFormService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CkOrderAchievementFormServiceImpl implements CkOrderAchievementFormService {
    @Autowired
    private CkOrderAchievementFormMapper ckOrderAchievementFormMapper;
    protected static final Logger logger = LoggerFactory.getLogger(CkOrderAchievementFormServiceImpl.class);
    @Override
    public  Map<String, CkOrderAchievementForm> selectAll() {
        List<CkOrderAchievementForm> ckOrderAchievementForms = ckOrderAchievementFormMapper.selectAll();
        Map<String, CkOrderAchievementForm> ckOrderAchievementFormHashMap = new HashMap<>();
        ckOrderAchievementForms.stream().forEach(ckOrderAchievementForm -> {
            String collectorId = ckOrderAchievementForm.getCollectorId();
            ckOrderAchievementFormHashMap.put(collectorId,ckOrderAchievementForm);
        });
        return ckOrderAchievementFormHashMap;
    }

    @Override
    public void insertForeach(List<CkOrderAchievementForm> addCkOrderAchievementForm) {
        ckOrderAchievementFormMapper.insertForeach(addCkOrderAchievementForm);
    }

    @Override
    public void updateForeach(List<CkOrderAchievementForm> updateCkOrderAchievementForm) {
        ckOrderAchievementFormMapper.updateForeach(updateCkOrderAchievementForm);
    }



    @Override
    public List<CkOrderAchievementForm> select(String collectorId, String collectorName,String dataTime)  {
        logger.info("催收员查询管理开始,参数为:collectorId:"+collectorId+"collectorName:"+collectorName+"dataTime:"+dataTime);
        List<CkOrderAchievementForm> ckOrderAchievementForms =new ArrayList<>();
        try {
            dataTime="%"+dataTime+"%";
            Map<String, Object> params = new HashMap<>();
            if (StringUtils.isNoneEmpty(collectorId)) {
                params.put("collectorId",collectorId);
            }
            if (StringUtils.isNoneEmpty(collectorName)) {
                params.put("collectorName",collectorName);
            }
            params.put("dataTime",dataTime);
            ckOrderAchievementForms = ckOrderAchievementFormMapper.findBySerialNumbers(params);
           /* List<CkOrderRecoveryData> ckOrderRecoveryDatas=ckOrderRecoveryDataMapper.findByCollectorIdAndCollectorNameAndDataTime(collectorId,collectorName,dataTime);
            Map<String, List<String>> receiptNumsMap = new HashMap<>();
            for (CkOrderRecoveryData ckOrderRecoveryData : ckOrderRecoveryDatas) {
                String customerServiceId = ckOrderRecoveryData.getCustomerServiceId();
                String customerServiceName = ckOrderRecoveryData.getCustomerServiceName();
                if (StringUtils.isEmpty(customerServiceId) ||StringUtils.isEmpty(customerServiceName)) {
                    logger.info("催收员查询,案件号:"+ckOrderRecoveryData.getSerialNumber()+",的催收员信息为空");
                    continue;
                }
                String key =customerServiceId+"@"+customerServiceName;
                String receiptNum = ckOrderRecoveryData.getReceiptNum();
                List<String>receiptNums=null;
                if (CollectionUtils.isEmpty(receiptNumsMap.get(key))) {
                    receiptNums = new ArrayList<>();
                } else {
                    receiptNums=receiptNumsMap.get(key);
                }
                receiptNums.add(receiptNum);
                receiptNumsMap.put(key,receiptNums);
            }
            for (Map.Entry<String, List<String>> stringListEntry : receiptNumsMap.entrySet()) {
                String key = stringListEntry.getKey();
                List<String> receiptNums = stringListEntry.getValue();
                Map<String, Object> params = new HashMap<>();
                params.put("receiptNums",receiptNums);
                params.put("dataTime",dataTime);
                CkOrderAchievementForm ckOrderAchievementForm= ckOrderLoanIntelligenceDivisionMapper.findBySerialNumbers(params);
                String[] split = key.split("@");
                ckOrderAchievementForm.setCollectorId(split[0]);
                ckOrderAchievementForm.setCollectorName(split[1]);
                ckOrderAchievementForms.add(ckOrderAchievementForm);
            }*/
            logger.info("催收员查询管理结束,返回值为:"+ JSON.toJSONString(ckOrderAchievementForms));
        } catch (Exception e) {
            logger.error("催收员查询管理失败",e);
        }
        return ckOrderAchievementForms;
    }

    @Override
    public PageInfo select(Map<String,Object> params)  {
        logger.info("催收员查询管理开始,参数为:"+JSON.toJSONString(params));
        PageInfo result =null;
        try {
            String collectorId = null==params.get("collectorId")?null:params.get("collectorId").toString();
            String collectorName = null==params.get("collectorName")?null:params.get("collectorName").toString();

            int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
            int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10").toString());
            PageHelper.startPage(page, pageSize);
            List<CkOrderAchievementForm> ckOrderAchievementForms= ckOrderAchievementFormMapper.select(collectorId,collectorName);

            result = new PageInfo(ckOrderAchievementForms);

            logger.info("催收员查询管理结束,返回值为:"+ JSON.toJSONString(result));
        } catch (Exception e) {
            logger.error("催收员查询管理失败",e.getMessage());
        }
        return result;
    }

    /**
     * 获取当月最后一天数据
     * @param endTime
     * @return
     * @throws ParseException
     */
    private String getLastTime(String endTime) throws ParseException {
        String[] startSplit = endTime.split("-");
        int year = Integer.parseInt(startSplit[0]);
        int month = Integer.parseInt(startSplit[1]);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month);
        int minimum = calendar.getMinimum(Calendar.DATE);
        calendar.set(Calendar.DAY_OF_MONTH,minimum-1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return  simpleDateFormat.format(calendar.getTime());
    }
    /**
     * 获取当月最后一天数据
     * @param startTime
     * @return
     * @throws ParseException
     */
    private String getFirstTime(String startTime) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(startTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        return simpleDateFormat.format(calendar.getTime());
    }


    /**
     * 获取两个日期之间的所有日期
     * @param startTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    private List<String> getBetweenDays(String startTime, String endTime) throws ParseException {
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            List<String> result = new ArrayList<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date startTimeParse = simpleDateFormat.parse(startTime);
            Date endTimeParse = simpleDateFormat.parse(endTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTimeParse);
            startCalendar.add(Calendar.DAY_OF_YEAR,1);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTimeParse);
            result.add(simpleDateFormat.format(startTimeParse));
            while (startCalendar.before(endCalendar)) {
                result.add(simpleDateFormat.format(startCalendar.getTime()));
                startCalendar.add(Calendar.DAY_OF_YEAR,1);
            }
            return result;
        } else {
            return null;
        }
    }
}
